package com.zlx.sharelive.activity;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.LoginBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.utils.StringUt;

import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imlib.RongIMClient;

/**
 * 登录
 */
public class LoginAc extends BaseAc {

    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_pass)
    EditText et_pass;
    @BindView(R.id.tv_area_code)
    TextView tv_area_code;

    @Override
    protected int getLayoutId() {
        return R.layout.ac_login;
    }

    @Override
    public void initViews() {
        super.initViews();


    }

    @OnClick({R.id.tv_registered, R.id.bt_login, R.id.tv_forget_pass, R.id.ll_area_code})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.ll_area_code:
                startActivityForResult(new Intent(this, AreaCodeListAc.class), 20);
                break;
            //注册
            case R.id.tv_registered:
                startActivity(new Intent(this, RegisterAc.class));
                break;
            //登录
            case R.id.bt_login:
//                startActivity(new Intent(this, MainAc.class));
                if (StringUt.isEmpty(et_phone.getText().toString().trim())) {
                    Toast.makeText(this,
                           "手机号不可为空",
                            Toast.LENGTH_SHORT).show();
                    return;
                } else if (StringUt.isEmpty(et_pass.getText().toString().trim())) {
                    Toast.makeText(this,
                            getResources().getString(R.string.password_cannot_be_empty),
                            Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    showLoading();
                    userLogin();
                }
                break;
            //忘记密码
            case R.id.tv_forget_pass:
                startActivity(new Intent(this, ForgetPassAc.class));
                break;
        }
    }

    /**
     * 登录
     */
    private void userLogin() {
        ApiUtil.getLoginApi().user_login((tv_area_code.getText().toString().trim() + et_phone.getText().toString().trim()).replace("+", ""),
                et_pass.getText().toString().trim()).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<LoginBean>>() {
            @Override
            public void onSuccess(ApiResponse<LoginBean> data) {
                if (data.getData().getCode() == 0) {
                    //成功
                    SPUtil.setObjectToShare(LoginAc.this,
                            data.getData().getInfo(), Constants.USERINFO);
                    SPUtil.put(LoginAc.this, Constants.SP_TOKEN, data.getData().getInfo().get(0).getToken());
                    SPUtil.put(LoginAc.this, Constants.SP_ID, data.getData().getInfo().get(0).getId());
                    SPUtil.put(LoginAc.this, Constants.SP_IM_TOKEN, data.getData().getInfo().get(0).getImToken());
                    SPUtil.put(LoginAc.this, Constants.SP_SAVE_PHONE, tv_area_code.getText().toString().trim() + et_phone.getText().toString().trim());
                    SPUtil.put(LoginAc.this, Constants.SP_VIP, data.getData().getInfo().get(0).getIsvip());
                    SPUtil.put(LoginAc.this, Constants.SP_INVITE_CODE, data.getData().getInfo().get(0).getInviteCode());
                    initIm(data.getData().getInfo().get(0).getImToken());
                } else {
                    showSuccess();
                    Toast.makeText(LoginAc.this,
                            data.getData().getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFail(String msg) {
                super.onFail(msg);
                showSuccess();
            }
        }));
    }

    private void initIm(String imToken) {
        RongIMClient.connect(imToken, new RongIMClient.ConnectCallback() {
            @Override
            public void onDatabaseOpened(RongIMClient.DatabaseOpenStatus code) {
                //消息数据库打开，可以进入到主页面
                showSuccess();
                Log.d("ret", "joker   登录成功IM1");
            }

            @Override
            public void onSuccess(String s) {
                //连接成功
                showSuccess();
                Log.d("ret", "joker   登录成功IM2");
                startActivity(new Intent(LoginAc.this, MainAc.class));
                finish();
            }

            @Override
            public void onError(RongIMClient.ConnectionErrorCode errorCode) {
                showSuccess();
                if (errorCode.equals(RongIMClient.ConnectionErrorCode.RC_CONN_TOKEN_INCORRECT)) {
                    //从 APP 服务获取新 token，并重连
                    Log.d("ret", "joker   登录失败1" + errorCode);
                } else {
                    //无法连接 IM 服务器，请根据相应的错误码作出对应处理
                    Log.d("ret", "joker   登录失败2" + errorCode);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null == data) {
            return;
        }
        if (resultCode == 30) {
            tv_area_code.setText(data.getStringExtra("code"));
        }
    }


}
